package com.chc.web.house_building.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.chc.utils.Msg;
import com.chc.web.house_building.entity.HouseBuilding;
import com.chc.web.house_building.entity.HouseBuildingParm;
import com.chc.web.house_building.service.HouseBuildingService;
import com.chc.web.house_unit.entity.HouseUnit;
import com.chc.web.house_unit.mapper.HouseUnitMapper;
import com.chc.web.house_unit.service.HouseUnitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Created with IntelliJ IDEA
 *
 * @Author: chc
 * @Date: 2022/01/11/20:18
 * @Description:
 */
@RestController
@RequestMapping("/api/HouseBuilding")
public class HouseBuildingController {

    @Autowired
    private HouseBuildingService houseBuildingService;

    @Autowired
    private HouseUnitMapper houseUnitMapper;

    /**
     * 查询列表
     * */
    @GetMapping("/list")
    public Msg list(HouseBuildingParm parm){
        IPage<HouseBuilding> list = houseBuildingService.getList(parm);
        return Msg.success("查询成功",list);
    }

    /**
     * 给单元查询列表
     * */
    @GetMapping("/unitList")
    public Msg unitList(){
        List<HouseBuilding> list = houseBuildingService.list();
        return Msg.success("查询成功",list);
    }

    /**
     * 新增栋数
     * */
    @PostMapping
    @PreAuthorize("hasAuthority('sys:houseBuilding:add')")
    public Msg save(@RequestBody HouseBuilding houseBuilding){
        boolean b = houseBuildingService.save(houseBuilding);
        if(b){
            return Msg.success("新增楼栋成功!");
        }
        return Msg.error("新增楼栋失败!");
    }

    /**
     * 编辑
     * */
    @PutMapping
    @PreAuthorize("hasAuthority('sys:houseBuilding:edit')")
    public Msg edit(@RequestBody HouseBuilding houseBuilding){
        boolean b = houseBuildingService.updateById(houseBuilding);
        if(b){
            return Msg.success("编辑楼栋成功!");
        }
        return Msg.error("编辑楼栋失败!");
    }

    /**
     * 编辑
     * */
    @DeleteMapping("/{buildId}")
    @PreAuthorize("hasAuthority('sys:houseBuilding:delete')")
    public Msg delete(@PathVariable("buildId") Long buildId){
        QueryWrapper<HouseUnit> query = new QueryWrapper();
        query.lambda().eq(HouseUnit::getBuildId,buildId);
        List<HouseUnit> houseUnits = houseUnitMapper.selectList(query);
        if (houseUnits.size() > 0 ){
            return Msg.error("该楼栋已经有单元,不能删除");
        }
        boolean b = houseBuildingService.removeById(buildId);
        if(b){
            return Msg.success("删除楼栋成功!");
        }
        return Msg.error("删除楼栋失败!");
    }
}
